# -*- coding: utf-8 -*-
# @File     : validators.py
# @Author   : bingjia
# @Time     : 2020/7/29 15:37
# @Desc     : User验证

import re

from django.utils.translation import ugettext as _
from django.core import validators as core_validators

from .models import User
from ..base.api import serializers
from ..base.api.exceptions import ValidationError


class UserValidator(serializers.ModelSerializer):
    class Meta:
        model = User
        fields = ("username", "full_name", "color", "bio", "lang",
                  "theme", "timezone", "is_active")

    def validate_username(self, attrs, source):
        value = attrs[source]
        validator = core_validators.RegexValidator(re.compile('^[\w.-]+$'), _("invalid username"),
                                                   _("invalid"))

        try:
            validator(value)
        except ValidationError:
            raise ValidationError(_("Required. 255 characters or fewer. Letters, "
                                    "numbers and /./-/_ characters'"))

        if (self.object and
                self.object.username != value and
                User.objects.filter(username=value).exists()):
            raise ValidationError(_("Invalid username. Try with a different one."))

        return attrs


class UserAdminValidator(serializers.ModelSerializer):
    class Meta:
        model = User
        fields = ("username", "full_name", "color", "bio", "lang",
                  "theme", "timezone", "is_active")

    def validate_username(self, attrs, source):
        value = attrs[source]
        validator = core_validators.RegexValidator(re.compile('^[\w.-]+$'), _("invalid username"),
                                                   _("invalid"))

        try:
            validator(value)
        except ValidationError:
            raise ValidationError(_("Required. 255 characters or fewer. Letters, "
                                    "numbers and /./-/_ characters'"))

        if (self.object and
                self.object.username != value and
                User.objects.filter(username=value).exists()):
            raise ValidationError(_("Invalid username. Try with a different one."))

        return attrs
